#include <string.h>
#include <stddef.h>
#include "dap_setting.h"
#include "esp_log.h"
#include "custom_nvs.h"
static MdLink_DAP_Setting_t MdLink_DAP_Setting;

esp_err_t load_dap_setting(void)
{
    /*从NVS中读取dap设置*/
    esp_err_t ret;
    ret = custom_nvs_read(DAP_SETTING, &MdLink_DAP_Setting, sizeof(MdLink_DAP_Setting_t));
    if(MdLink_DAP_Setting.magic!= DAP_SETTING_MAGIC)
    {
        /*如果读取失败或者magic不匹配，则使用默认设置*/
        //ESP_LOGI("dap_setting", "load default dap setting");
        dap_setting_load_default(true);
    }
    //memcpy(&MdLink_DAP_Setting, &default_setting, sizeof(MdLink_DAP_Setting_t));
    // ESP_LOGI("dap_setting", "jtag_port_mode:%d, swd_port_mode:%d, power_vref:%.2f, power_on:%d, port_on:%d, reset:%d", MdLink_DAP_Setting.jtag_port_mode, MdLink_DAP_Setting.swd_port_mode, MdLink_DAP_Setting.power.vref, MdLink_DAP_Setting.power.power_on, MdLink_DAP_Setting.power.port_on, MdLink_DAP_Setting.reset);
    return ret;
}
/*
 * @brief 保存dap设置到NVS
 * @param pDap_Setting: 要保存的dap设置
 * @param is_to_flash: 是否保存到flash
 */
esp_err_t set_dap_setting(pMdLink_DAP_Setting_t pDap_Setting, bool is_to_flash)
{
    if (pDap_Setting == NULL) {
        goto load;
    }

    memcpy(&MdLink_DAP_Setting, pDap_Setting, sizeof(MdLink_DAP_Setting_t));

load:
    esp_err_t ret=ESP_OK;
    //保存设置到NVS
    if (is_to_flash) {
        ret = custom_nvs_write(DAP_SETTING, &MdLink_DAP_Setting, sizeof(MdLink_DAP_Setting_t));
    }
    return ret;
}
esp_err_t dap_setting_load_default(bool is_to_flash)
{
    MdLink_DAP_Setting = DAP_SETTING_DEFAULT();

    return set_dap_setting(NULL, is_to_flash);
}

pMdLink_DAP_Setting_t get_dap_setting(void)
{
    return &MdLink_DAP_Setting;
}
